package com.atguigu.gmall.user.controller;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author: lx
 * @Time: 10:04
 * @Description:
 */
@RestController
@RequestMapping("/api/user/passport")
public class UserApiController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserInfoService userInfoService;
    //提交登录表单
    @PostMapping("/login")
    public Result login(@RequestBody UserInfo userInfo){//登录名 密码

        if(null == userInfo || "".equals(userInfo.getLoginName().trim())){
            return Result.fail().message("用户名不能为空");
        }
        if(null == userInfo || "".equals(userInfo.getPasswd().trim())){
            return Result.fail().message("密码不能为空");
        }
        //检验用户名密码是否正确
        userInfo = userInfoService.login(userInfo);
        if(null != userInfo){
            //准备token
            Map map = new HashMap<>();
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            map.put("token",uuid);
            map.put("nickName",userInfo.getNickName());
            //  Map user:login = new HashMap  存活
            //   user:login.put(uuid,UserInfo)
            redisTemplate.opsForValue().set(
                    RedisConst.USER_LOGIN_KEY_PREFIX + uuid,userInfo,
                    RedisConst.USERKEY_TIMEOUT,TimeUnit.SECONDS);
            //昵称
            return Result.ok(map);
        }
        return Result.fail().message("用户名或密码不正确");
    }

    //查询用户地址
    @GetMapping("/findUserAddressList")
    public List<UserAddress> findUserAddressList(){
        return userInfoService.findUserAddressList();
    }
}
